<script setup>
import { onMounted,ref,reactive} from 'vue'
import {queryAllFM,updateFM,addFM,deleteFM} from "@/api/fm";
import {ElMessage,ElMessageBox} from "element-plus";
import axios from "axios";
const currentPage = ref(1)
const pageSize = ref(10)
const background = ref(true);
const total = ref(0);
const tableData = ref([]);
const formInline = ref({
  title: ''
})
// 对话框控制
const dialogVisible = ref(false)
const mode = ref('add') // add/edit/view
const formData = ref({
  id: null,
  title: '',
  coverImage: '',
  audioUrl: '',
  categoryId: null,
  createTime: '',
  categoryName:''
})
// 添加选中的行数据
const selectedRows = ref([]);
const uploadRef = ref(null)
// 定义等级选项
const levelOptions = ref([])
const searchFM = async () => {
  let response;
  try {
   response = await axios({
      url: 'api/articleCategory/search',
      method: 'get',
      params: {
        pageNum:1,
        pageSize:10
      }
    })
    console.log('分类数据:', response)
    if (response.data.code) {
      levelOptions.value = response.data.data.rows.map(item => ({
        id: item.id,
        name: item.categoryName
      }))
    }
  } catch (e) {
    ElMessage.error(response.data.msg || '请求失败')
  }
}

const handleSuccess = (response) => {
  if (response.code === 1) {
    formData.value.coverImage = 'http://localhost:8080' + response.data
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(response.msg || '上传失败')
  }
}

const handleError = (error) => {
  console.error('上传失败:', error)
  ElMessage.error('上传失败，请重试')
}

const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleImageError = (e) => {
  e.target.style.display = 'none'
}


// 增加音频上传相关逻辑
const beforeAudioUpload = (file) => {
  const isAudio = file.type.startsWith('audio/')
  if (!isAudio) {
    ElMessage.error('只能上传音频文件!')
    return false
  }
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('音频大小不能超过 5MB!')
    return false
  }
  return true
}

const handleAudioSuccess = (response) => {
  if (response.code === 1) {
    formData.value.audioUrl = 'http://localhost:8080' + response.data
    ElMessage.success('音频上传成功')
  } else {
    ElMessage.error(response.msg || '音频上传失败')
  }
}






// 表单验证规则
const formRules = reactive({
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }]
})

onMounted(() => {
  search();
  searchFM()
})
const search=async ()=>{
  const restult = await queryAllFM(currentPage.value,pageSize.value,formInline.value.title)
  console.log(restult)
  if(restult.code){
    tableData.value = restult.data.rows;
    total.value = restult.data.total
  }else{
    ElMessage.error(restult.msg)
  }
}
// 通用提交处理
const handleSubmit = () => {
  if (mode.value === 'add') {
    handleAddSubmit()
  } else if (mode.value === 'edit') {
    handleEditSubmit()
  }
}
// 提交添加
const handleAddSubmit = async () => {
  try {
    const payload = {
      ...formData.value,
      categoryId: Number(formData.value.categoryId)
    }
    const result = await addFM(payload);
    if (result.code === 1) {
      ElMessage.success('添加成功');
      dialogVisible.value = false;
      search();
    } else {
      ElMessage.error(result.msg || '添加失败');
    }
  } catch (error) {
    ElMessage.error('添加请求失败');
  }
}

// 提交编辑
const handleEditSubmit = async () => {
  try {
    const payload = {
      ...formData.value,
      categoryId: Number(formData.value.categoryId)
    };
    const result = await updateFM(payload);
    if (result.code === 1) {
      ElMessage.success('更新成功');
      dialogVisible.value = false;
      search();
    } else {
      ElMessage.error(result.msg || '更新失败')
    }
  } catch (error) {
    ElMessage.error('更新请求失败')
  }
}

// 打开添加对话框
const openAddDialog = () => {
  mode.value = 'add'
  formData.value = {
    id: null,
    title: '',
    coverImage: '',
    audioUrl: '',
    categoryId: null,
    createTime: '',
    categoryName:''
  }
  if (levelOptions.value.length ===0){
    searchFM().then(() => {
      dialogVisible.value = true
    })
  }else {
    dialogVisible.value = true
  }
}

// 打开编辑对话框
const openEditDialog = (row) => {
  mode.value = 'edit'
  formData.value = { ...row, createTime: new Date().toISOString().replace('T', ' ').substring(0, 19),
  categoryId: row.categoryId

  }
  // 强制刷新分类数据
  searchFM().finally(() => {
    dialogVisible.value = true
  })
}

// 打开详情对话框
const openViewDialog = (row) => {
  mode.value = 'view'
  formData.value = { ...row,
    categoryId:row.categoryId
    }
  dialogVisible.value = true
}

// 模式映射配置
const modeMap = reactive({
  add: { title: '添加FM', submit: handleAddSubmit },
  edit: { title: '编辑FM', submit: handleEditSubmit },
  view: { title: 'FM详情' }
})


const handleDelete = async (idOrRows) => {
  // 统一处理为数组
  let ids = []
  // 数据类型转换逻辑
  if (typeof idOrRows === 'number') {
    ids = [idOrRows]
  } else if (Array.isArray(idOrRows)) {
    ids = idOrRows.map(item => Number(item.id))
  } else {
    ids = selectedRows.value.map(item => Number(item.id))
  }

  try {
    await ElMessageBox.confirm('确定删除选中数据？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const result = await deleteFM(ids)
    if (result.code === 1) {
      ElMessage.success('删除成功')
      // 清空选中项
      selectedRows.value = []
      search()
    } else {
      ElMessage.error(result.msg || '删除失败')
    }
  } catch (error) {
    console.log('取消删除')
  }
}

const handleSizeChange = (val) => {
  search()
}
const handleCurrentChange = (val) => {
  search()
}
</script>

<template>
  <el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-form-item label="FM标题">
      <el-input v-model="formInline.title" placeholder="请输入FM标题" clearable />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="search">搜索</el-button>
      <el-button type="primary" @click="openAddDialog">+添加FM</el-button>
      <el-button type="danger" @click="handleDelete">-批量删除</el-button>
    </el-form-item>
  </el-form>




  <el-table :data="tableData" style="width: 100%"  @selection-change="val => selectedRows = val">
    <el-table-column type="selection"/>
    <el-table-column label="id" property="id"/>
    <el-table-column label="标题" property="title"/>
    <el-table-column label="列表图" property="coverImage">
      <template #default="scope">
        <div class="image-container">
          <img
              v-if="scope.row.coverImage"
              :src="scope.row.coverImage"
              @error="handleImageError"
              :alt="scope.row.title"
          >
          <div v-else class="image-placeholder">
            <el-icon><Picture /></el-icon>
          </div>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="动态音频" property="audioUrl">
      <template #default="scope">
        <div class="audio-cell">
          <audio
              v-if="scope.row.audioUrl"
              :src="scope.row.audioUrl"
              controls
          />
          <div v-else class="audio-placeholder">
            <el-icon><Headset /></el-icon>
            <span>暂无音频</span>
          </div>
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="categoryId" label="FM类型">
      <template #default="scope">
        {{ scope.row.articleCategory ? scope.row.articleCategory.categoryName : '未分类' }}
      </template>
    </el-table-column>
    <el-table-column label="创建时间" property="createTime"/>
    <el-table-column label="操作" >
      <template #default="scope">
        <el-button type="warning" size="mini"  @click="openViewDialog(scope.row)">详情</el-button>
        <el-button type="primary" size="mini" @click="openEditDialog(scope.row)">编辑</el-button>
        <el-button type="danger" size="mini" @click="handleDelete(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 通用对话框 -->
  <el-dialog
      v-model="dialogVisible"
      :title="modeMap[mode].title"
      width="40%"
  >
    <el-form
        :model="formData"
        label-width="100px"
        :disabled="mode === 'view'"
    >
      <!-- 查看模式显示ID和创建时间 -->
      <template v-if="mode === 'view'">
        <el-form-item label="FM ID">
          <el-input v-model="formData.id" readonly />
        </el-form-item>
      </template>

      <!-- 公共字段 -->
      <el-form-item label="标题" prop="title" :rules="formRules.title">
        <el-input v-model="formData.title" />
      </el-form-item>

      <el-form-item label="列表图" prop="coverImage">
        <el-upload
            ref="uploadRef"
            class="avatar-uploader"
            action="/api/img/upload"
            :show-file-list="false"
            :on-success="handleSuccess"
            :on-error="handleError"
            :before-upload="beforeUpload"
        >
          <img v-if="formData.coverImage" :src="formData.coverImage" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item label="音频文件">
        <el-upload
            v-if="mode !== 'view'"
            class="audio-uploader"
            action="/api/img/upload"
            :show-file-list="false"
            :before-upload="beforeAudioUpload"
            :on-success="handleAudioSuccess"
        >
          <el-button type="primary">
            <el-icon class="el-icon--right"><Upload /></el-icon>
            上传音频
          </el-button>
        </el-upload>
        <audio
            v-if="formData.audioUrl"
            :src="formData.audioUrl"
            controls
            class="audio-preview"
        />
      </el-form-item>
      <el-form-item label="FM类型" prop="categoryId">
        <el-select v-model="formData.categoryId" placeholder="请选择FM类型">
          <el-option
              v-for="level in levelOptions"
              :key="level.id"
              :label="level.name"
              :value="level.id" />
        </el-select>
      </el-form-item>



      <!-- 在对话框的表单中修改这部分 -->
      <el-form-item label="创建时间" v-if="mode === 'view'">
        <el-date-picker
            v-model="formData.createTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            readonly
            disabled
        />
      </el-form-item>

      <!-- 添加编辑时的时间字段（如果需要编辑时间） -->
      <el-form-item label="创建时间" v-else-if="mode === 'edit'">
        <el-date-picker
            v-model="formData.createTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item label="创建时间" v-else-if="mode === 'add'">
        <el-date-picker
            v-model="formData.createTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button
          v-if="mode !== 'view'"
          type="primary"
          @click="handleSubmit">确认
      </el-button>
    </template>
  </el-dialog>



  <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                            :page-sizes="[10, 20, 30, 40]" :size="size" :disabled="disabled" :background="background"
                            layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"/>
</template>

<style scoped>
/* 全局边距调整 */
.demo-form-inline {
  margin-bottom: 20px;
}

/* 表单元素间距调整 */
.demo-form-inline .el-form-item {
  margin-right: 20px;
  margin-bottom: 15px;
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
  margin-right: 10px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

/* 按钮组间距 */
.el-button + .el-button {
  margin-left: 12px;
}

/* 表格调整 */
.el-table {
  margin-top: 20px;
  margin-bottom: 20px;
}

/* 分页组件调整 */
.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

/* 对话框表单样式 */
.el-form-item {
  margin-bottom: 22px;
}

.el-form-item:last-child {
  margin-bottom: 0;
}

/* 音频控件宽度适配 */
audio {
  width: 100%;
}
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}
/* 统一图片容器尺寸 */
.image-container {
  width: 100px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

/* 修正真实图片样式 */
.el-table .cell img {
  width: 100%;
  height: 100%;
  object-fit: contain;  /* 保持比例填充 */
}

/* 调整占位符为绝对定位 */
.image-placeholder {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}

/* 添加父级对齐容器 */
.el-table__cell > .cell {
  display: flex !important;
  justify-content: center;
  min-height: 62px; /* 包含边框高度 */
}

/* 统一悬停状态容器 */
.image-container:hover {
  transform: scale(1.8);
  z-index: 1000;
  transition: all 0.3s ease;
}


.audio-uploader {
  margin-bottom: 10px;
}

.audio-preview {
  width: 100%;
  margin-top: 10px;
  border-radius: 4px;
  background: #f5f7fa;
}

/* 统一上传按钮样式 */
.el-button :deep(.el-icon) {
  vertical-align: middle;
  margin-right: 5px;
}
/* 音频单元格样式 */
.audio-cell {
  max-width: 300px;
}

/* 音频控件样式 */
.audio-cell audio {
  width: 100%;
  height: 40px;
}

/* 音频占位符 */
.audio-placeholder {
  display: flex;
  align-items: center;
  color: #909399;
  padding: 8px;
  background: #f5f7fa;
  border-radius: 4px;
  .el-icon {
    margin-right: 8px;
    font-size: 1.2em;
    color: #409EFF;
  }
}

/* 统一操作按钮间距 */
.el-table .el-button {
  margin: 4px;
}
</style>